package com.yituo.mjworld.mvc.service.impl;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.yituo.mjworld.mvc.service.other.QiniuConfig;
import org.junit.jupiter.api.Test;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * 七牛接口模块
 * <p>
 * 相关文档地址:
 * https://developer.qiniu.com/kodo/sdk/1239/java#7
 */
@Service
public class QiniuServiceImpl {

  /**
   * 获取上传凭证
   *
   * @return
   */
  public String getToken(String fileType) {
    Auth auth = Auth.create(QiniuConfig.ACCESS_KEY, QiniuConfig.SECRET_KEY);
    String uuid = UUID.randomUUID().toString().replace("-", "");
    String token = auth.uploadToken(QiniuConfig.delta2017.BUCKET, null, 3600, new StringMap()
        .putNotEmpty("saveKey", uuid + fileType), true);
    return token;
  }

  /**
   * 删除七牛图片
   * <p>
   * 文档地址:
   * https://developer.qiniu.com/kodo/sdk/1239/java#rs-delete
   * 踩坑说明:
   * 1.Zone的域名有多个可配置项.比如华东区,华南区,
   * 2.删除后CDN缓存没有清空,因此客户端仍然可以见到相关的图片
   *
   * @param key 欲删除的文件名
   * @return
   */
  public boolean delete(String key) {
    System.out.println(key);
    Configuration cfg = new Configuration(Zone.zone2());
    Auth auth = Auth.create(QiniuConfig.ACCESS_KEY, QiniuConfig.SECRET_KEY);
    BucketManager bucketManager = new BucketManager(auth, cfg);
    try {
      bucketManager.delete(QiniuConfig.delta2017.BUCKET, key);
    } catch (QiniuException ex) {
      //如果遇到异常，说明删除失败
//      System.err.println(ex.code());
//      System.err.println(ex.response.toString());
      return false;
    }
    return true;
  }


  /**
   * 获取URL中的key值
   *
   * @return
   */
  @Test
  public void test() {
    String url = "http://aaaa/aaa.jpg";
    System.out.println(getFileNameForUrl(url));
    String localpath = "F:\\1.png";
    System.out.println(getFileNameForUrl(localpath));
  }

  /**
   * 获取URL中的
   *
   * @param url 欲获取的URL中的文件名
   * @return
   */
  public String getFileNameForUrl(String url) {
    return url.substring(url.lastIndexOf("/") + 1, url.length());
  }

  /**
   * 获取全Path中的文件名
   *
   * @param localPath 本地的文件全路径
   * @return
   */
  public String getFileNameForPath(String localPath) {
    return localPath.substring(localPath.lastIndexOf("\\") + 1, localPath.length());
  }


  /**
   * 上传二维码
   * <p>
   * doc地址如下:
   * <p>
   * https://developer.qiniu.com/kodo/sdk/1239/java#upload-file
   *
   * @return 上传成功返回外链URL, 上传失败返回null
   */
  public String uploadQrcode(String localPath) {
    Configuration cfg = new Configuration(Zone.zone2());
    UploadManager uploadManager = new UploadManager(cfg);
    //如果是Windows情况下，格式是 D:\\qiniu\\test.png
    //String localFilePath = "/home/qiniu/test.png";
    //默认不指定key的情况下，以文件内容的hash值作为文件名
    String key = getFileNameForPath(localPath);
    Auth auth = Auth.create(QiniuConfig.ACCESS_KEY, QiniuConfig.SECRET_KEY);
    String upToken = auth.uploadToken(QiniuConfig.userQrcode.BUCKET, null, 3600, new StringMap()
        .putNotEmpty("saveKey", key), true);
    try {
      Response response = uploadManager.put(localPath, key, upToken);
      // 解析上传成功的结果
      DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
      System.out.println(putRet.key);
      System.out.println(putRet.hash);
      return "http://" + QiniuConfig.userQrcode.DOMAIN + "/" + putRet.key;
    } catch (QiniuException ex) {
      Response r = ex.response;
      System.err.println(r.toString());
      try {
        System.err.println(r.bodyString());
      } catch (QiniuException ex2) {
        //ignore
      }
    }
    return null;
  }
}
